﻿using System;
using System.Collections.Generic;
using System.Text;
using reactiveBT.Utilities;

namespace reactiveBT.BT
{
    /// <summary>
    /// 并行分支节点
    /// 首次或Reset后Tick将执行所有子节点，仅当所有子结点返回值为Success或Failure时才返回Success
    /// 向上传递Abort信息，若有子节点返回Continue时，该节点返回Continue
    /// 非首次Tick将仅执行上次Tick返回Continue的节点
    /// </summary>
    public class Parallel : Branch
    {
        List<BTState> resList = null;
        public override BTState Tick(int BTid)
        {
            if (resList == null)
            {
                resList = new List<BTState>();
                for (int i = 0; i < children.Count; i++)
                {
                    resList.Add(children[i].Tick(BTid));
                }
            }
            else
            {
                for (int i = 0;i < resList.Count;i++)
                {
                    if (resList[i] == BTState.Continue)
                    {
                        resList[i] = children[i].Tick(BTid);
                    }
                    if (resList[i] == BTState.Abort)
                    {
                        needToReset = true;
                        return BTState.Abort;
                    }
                }
            }
            bool hadRunningNode = false;
            for (int i = 0; i < resList.Count; i++)
            {
                switch(resList[i])
                {
                    case BTState.Continue:
                        hadRunningNode = true;
                        break;
                    case BTState.Abort:
                        needToReset = true;
                        return BTState.Abort;
                    default:
                        continue;
                }
            }
            return hadRunningNode ? BTState.Continue : BTState.Success;
        }
        protected override void ResetSelf()
        {
            base.ResetSelf();
        }
    }
}
